package com.zzl.alligator.management.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zzl.alligator.common.constant.ProjectProperties;
import com.zzl.alligator.common.constant.SystemConstants;
import com.zzl.alligator.common.util.SecurityUtils;
import com.zzl.alligator.common.util.StringUtils;
import com.zzl.alligator.framework.exception.CustomException;
import com.zzl.alligator.management.system.domain.SysPost;
import com.zzl.alligator.management.system.domain.SysRole;
import com.zzl.alligator.management.system.domain.SysUser;
import com.zzl.alligator.management.system.domain.SysUserPost;
import com.zzl.alligator.management.system.domain.SysUserRole;
import com.zzl.alligator.management.system.mapper.SysPostMapper;
import com.zzl.alligator.management.system.mapper.SysRoleMapper;
import com.zzl.alligator.management.system.mapper.SysUserMapper;
import com.zzl.alligator.management.system.mapper.SysUserPostMapper;
import com.zzl.alligator.management.system.mapper.SysUserRoleMapper;
import com.zzl.alligator.management.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户service
 *
 * @author zhouziliang
 * @since 2020/6/25
 */
@Service
@Slf4j
public class SysUserService implements ISysUserService {


    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysConfigService configService;

    @Autowired
    private SysUserAssistService userAssistService;


    /**
     * 根据条件 分页查找用户信息
     *
     * @param sysUser 查找条件
     * @return 用户信息列表
     */
    @Override
    public List<SysUser> findUserList(SysUser sysUser) {
        return userMapper.selectUserList(sysUser);
    }

    /**
     * 通过用户名查找用户
     *
     * @param name 用户姓名
     * @return 用户信息
     */
    @Override
    public SysUser findUserByName(String name) {
        return userMapper.selectUserByUserName(name);
    }

    /**
     * 根据用户Id 查找用户
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @Override
    public SysUser findUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    /**
     * 根据用户ID查找用户所属角色组
     *
     * @param userName 用户ID
     * @return 角色组
     */
    @Override
    public String findUserRoleGroupByUserName(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (list == null) {
            return null;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }


    /**
     * 根据用户Id 查找部门Id
     *
     * @param userIds 用户ID列表
     * @return 部门ID
     */
    @Override
    public List<Long> getDeptIdsByUserIds(List<Long> userIds) {
        List<SysUser> userList = userMapper.selectUserListByIds(userIds);
        Set<String> deptSet = new HashSet<>();

        userList.stream().forEach(user -> {
            deptSet.add(String.valueOf(user.getDeptId()));
            String str = user.getDept().getAncestors();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
                String[] ds = str.split(",");
                deptSet.addAll(CollectionUtil.newArrayList(ds));
            }
        });
        return deptSet.stream().map(Long::valueOf).collect(Collectors.toList());
    }

    /**
     * 根据用户ID查找用户所属岗位组
     *
     * @param userName 用户名
     * @return 岗位列表
     */
    @Override
    public String findUserPostByUserId(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (list == null) {
            return null;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 检查用户账号是否唯一
     *
     * @param userName 用户账号
     * @return
     */
    @Override
    public String checkUserAccountUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return SystemConstants.NOT_UNIQUE;
        }
        return SystemConstants.UNIQUE;
    }

    /**
     * 检查手机号是否唯一
     *
     * @param user 用户
     * @return 检查结果
     */
    @Override
    public String checkPhoneNumUnique(SysUser user) {
        return checkUserUnique(user, userMapper.checkPhoneUnique(user.getPhonenumber()));
    }

    /**
     * 检查邮箱是否唯一
     *
     * @param user 用户
     * @return 检查结果
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        return checkUserUnique(user, userMapper.checkEmailUnique(user.getEmail()));
    }

    private String checkUserUnique(SysUser user, SysUser checkedUser) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = checkedUser;
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return SystemConstants.NOT_UNIQUE;
        }
        return SystemConstants.UNIQUE;
    }

    /**
     * 新增用户
     *
     * @param user 用户信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        userAssistService.insertUser(user.getUserId());
        return rows;
    }

    /**
     * 插入用户角色信息
     *
     * @param user
     */
    private void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 插入用户岗位信息
     *
     * @param user
     */

    private void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 更新用户 包含用户角色信息、岗位信息
     *
     * @param user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);

    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户
     * @return 修改条数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserAvatar(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resetUserPwd(SysUser user) {
        if (!ProjectProperties.getInstance().isAllowChangeAdminPassword()) {
            this.checkUserAllowed(user);
        }
        return userMapper.resetUserPwd(user);
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        return userMapper.deleteUserByIds(userIds);
    }


    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 批量导入用户
     *
     * @param userList      用户列表
     * @param updateSupport 是否覆盖上传
     * @param operName      操作用户
     * @return 更新结果
     */
    @Override
    public String importUser(List<SysUser> userList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.findConfigValueByConfigKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (updateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 更改用户状态
     *
     * @param user
     * @return
     */
    @Override
    public int changeUserStatus(SysUser user) {
        return userMapper.updateUserStatus(user);
    }

    /**
     * 根据部门ID查找用户
     *
     * @param deptId 部门ID
     * @return 部门直属用户
     */
    @Override
    @Cacheable(cacheNames = {"COMMON_CACHE"}, key = "#targetClass + '_findUserByDeptId_' + #p0")
    public List<SysUser> findUserByDeptId(Long deptId) {
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        return userMapper.selectUserOfDept(sysUser);
    }
}
